<!--
文件名: src/views/order/reservation/index.vue
功能: 预约信息管理列表页 (单选最终版)
描述: 恢复为与现有后端匹配的单选筛选模式。
-->
<template>
  <div class="app-container">
    <!-- 1. 筛选与操作区 -->
    <el-card shadow="never">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="query-form">
        <el-form-item label="预约人" prop="contact_name">
          <el-input v-model="queryParams.contact_name" placeholder="请输入姓名" clearable />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="queryParams.contact_phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="课题组" prop="contact_group">
          <el-input v-model="queryParams.contact_group" placeholder="请输入课题组" clearable />
        </el-form-item>

        <!-- 退回1：恢复为单选设备 -->
        <el-form-item label="预约设备" prop="device_id">
          <el-select v-model="queryParams.device_id" placeholder="请选择设备" clearable>
            <el-option
              v-for="device in deviceOptions"
              :key="device.id"
              :label="device.name"
              :value="device.id"
            />
          </el-select>
        </el-form-item>

        <!-- 退回2：恢复为单选状态 -->
        <el-form-item label="预约状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="预约日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 2. 数据表格区 -->
    <el-card shadow="never" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>预约列表</span>
          <el-button type="success" :icon="Download" @click="handleExport" :loading="exportLoading"
            >导出 Excel</el-button
          >
        </div>
      </template>

      <el-table v-loading="loading" :data="reservationList">
        <el-table-column label="ID" prop="id" width="180" align="center" />
        <el-table-column label="预约设备" prop="device.name" width="220" align="center" />
        <el-table-column label="预约人" prop="contact_name" width="100" align="center" />
        <el-table-column label="联系电话" prop="contact_phone" width="140" align="center" />
        <el-table-column label="课题组" prop="contact_group" width="200" align="center" />
        <el-table-column label="开始时间" prop="start_time" width="180" align="center" />
        <el-table-column label="结束时间" prop="end_time" width="180" align="center" />
        <el-table-column label="状态" prop="status" width="100" align="center">
          <template #default="scope">
            <el-tag :type="statusMap[scope.row.status]?.type || 'info'">
              {{ statusMap[scope.row.status]?.text || '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button
              v-if="['confirmed', 'ongoing'].includes(scope.row.status)"
              type="danger"
              link
              @click="handleCancel(scope.row)"
              >取消预约</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 退回3：恢复为简化版分页（之前已修改，保持即可） -->
      <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.page"
        :page-size="queryParams.size"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="getList"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  getReservationListApi,
  cancelReservationApi,
  getAllDevicesApi,
  exportReservationsApi,
} from '@/api'
import type { ReservationListParams, ReservationDetail } from '@/api/types/reservation'
import type { Device } from '@/api/types/device'
import { Search, Refresh, Download } from '@element-plus/icons-vue'

const loading = ref(true)
const exportLoading = ref(false)
const total = ref(0)
const queryFormRef = ref<FormInstance>()
const reservationList = ref<ReservationDetail[]>([])
const deviceOptions = ref<Device[]>([])
const dateRange = ref<[string, string] | null>(null)

// 退回4：恢复为单选的查询参数
const queryParams = reactive<ReservationListParams>({
  page: 1,
  size: 10,
  contact_name: undefined,
  contact_phone: undefined,
  contact_group: undefined,
  device_id: undefined,
  status: undefined,
  start_date: undefined,
  end_date: undefined,
})

const statusOptions = [
  { value: 'confirmed', label: '已确认' },
  { value: 'ongoing', label: '进行中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancelled', label: '已取消' },
  { value: 'timed_out', label: '已超时' },
]

const statusMap: Record<string, { text: string; type: 'success' | 'warning' | 'danger' | 'info' }> =
  {
    confirmed: { text: '已确认', type: 'success' },
    ongoing: { text: '进行中', type: 'warning' },
    completed: { text: '已完成', type: 'info' },
    cancelled: { text: '已取消', type: 'danger' },
    timed_out: { text: '已超时', type: 'danger' },
  }

const getList = async () => {
  loading.value = true
  try {
    queryParams.start_date = dateRange.value?.[0]
    queryParams.end_date = dateRange.value?.[1]
    const response = await getReservationListApi(queryParams)
    reservationList.value = response.items
    total.value = response.total
  } catch (error) {
    console.error('获取预约列表失败:', error)
  } finally {
    loading.value = false
  }
}

const getDevices = async () => {
  try {
    deviceOptions.value = await getAllDevicesApi()
  } catch (error) {
    console.error('获取设备选项失败:', error)
    deviceOptions.value = []
  }
}

const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/** 重置按钮操作 */
const handleReset = () => {
  queryFormRef.value?.resetFields()
  dateRange.value = null
  handleQuery()
}

const handleCancel = async (row: ReservationDetail) => {
  try {
    await ElMessageBox.confirm(`确认要取消用户 [${row.contact_name}] 的这条预约吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '我再想想',
      type: 'warning',
    })
    await cancelReservationApi(row.id)
    ElMessage.success('取消成功')
    getList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消操作')
    } else {
      console.error('取消预约失败:', error)
    }
  }
}

const handleExport = async () => {
  exportLoading.value = true
  try {
    const blob = await exportReservationsApi(queryParams)
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '预约信息报表.xlsx'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  getList()
  getDevices()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.query-form .el-select {
  min-width: 180px;
}
</style>
